<template>
  <Layout style="height: 100%;" class="main">
    <Sider hide-trigger collapsible :width="256" :collapsed-width="64" v-model="collapsed" class="left-sider"
           :style="{overflow: 'hidden'}">
      <side-menu accordion ref="sideMenu" :active-name="$route.name" :collapsed="collapsed" @on-select="turnToPage"
                 :menu-list="menuList">
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con">
          <!--<div v-show="!collapsed" class="logo_ttile">
            <img :src="main_title_img" class="main_title_img">
          </div>-->
          <img v-show="!collapsed" :src="main_title_img" class="max-logo" key="max-logo"/>
          <img v-show="collapsed" :src="'/vendors/images/' + main_logo" class="min-logo" key="min-logo"/>
        </div>
      </side-menu>
    </Sider>
    <Layout style="overflow: hidden;" id="main">
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">

          <user :user-avator="userAvator" :user-name="userName"/>

          <div class="message-div" @click="loginOut()" title="退出登录">
            <Icon type="md-log-out" :size="23"/>
          </div>

          <fullscreen v-model="isFullscreen" style="margin-right: 16px;cursor: pointer;"/>

        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <div class="tag-nav-wrapper">
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"/>
          </div>
          <Content class="content-wrapper">
            <keep-alive :include="cacheList">
              <router-view/>
            </keep-alive>
          </Content>
        </Layout>
      </Content>
      <Content class="main-bottom-con">
        <div class="main-bottom-con">
          <div class="main-bottom">
            <a href="http://www.jnaw.top" target="_blank" class="html-button">
              ©2019 AllView CWBU All Rights Reserved. v{{ version }}
            </a>
          </div>
        </div>
      </Content>
    </Layout>
  </Layout>
</template>
<script>

  import SideMenu from './components/side-menu'
  import HeaderBar from './components/header-bar'
  import TagsNav from './components/tags-nav'
  import User from './components/user'
  import Fullscreen from './components/fullscreen'
  import Language from './components/language'
  import {mapMutations, mapActions} from 'vuex'
  import {getNewTagList, getNextRoute, routeEqual} from '@/libs/util'
  import './main.less'
  import Cookies from 'js-cookie';
  import util from '../../libs/util';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import dbUtils from '../../libs/mod.local.db';
  import IndexDB from '../../libs/mod.indexDB';
  import baiduMap from '../../libs/mod.baiduMap';
  import os from '../../libs/mod.os';

  import im from '../../mod/im'
  import Consts from '../../assets/consts'

  import Log from '../../mod/log'
  let log = new Log('main')

  export default {
    name: 'Main',
    components: {
      SideMenu,
      HeaderBar,
      Language,
      TagsNav,
      Fullscreen,
      User
    },
    data () {
      return {
        collapsed: false, // 左侧菜单栏是否收起
        isFullscreen: false,
        version: util.version,
        uid: '',
        username: '',
        userName: '',
        menuList: [],
        main_title: Util.main_title,
        main_logo: Util.main_logo,
        main_title_img: '/vendors/images/' + Util.main_title_img,
        longitude: 0,// 定位信息
        latitude: 0,
        address: '',
      }
    },
    computed: {
      localMessage_unread () {
        return this.$store.state.app.localMessage_unread
      },
      tagNavList () {
        return this.$store.state.app.tagNavList
      },
      tagRouter () {
        return this.$store.state.app.tagRouter
      },
      userAvator () {
        return this.$store.state.app.userAvator
      },
//      userName () {
//        return this.$store.state.app.userName
//      },
      cacheList () {
        return this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []
      },
      /*menuList () {
       return this.$store.getters.menuList
       },*/
      local () {
        return this.$store.state.app.local
      }
    },
    watch: {
      '$route' (newRoute) {
        this.setBreadCrumb(newRoute.matched)
        this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
      }
    },
    created () {
      var _this = this;
      _this.getMenuList();
      var title = Util.title(); // 页面标题
      var page_icon = Util.page_icon; // 页面ico
      window.document.title = title;
      // 设置ico
      var linkEle = document.getElementById("link_icon_id");
      linkEle.href = '/vendors/images/' + page_icon;
      linkEle.type = '';
      linkEle.type = 'image/x-icon';

      var userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        var obj = Utils.toJson(userInfo);
        _this.userName = obj.name || '';
      }
    },
    mounted () {
      var _this = this;
      /**
       * @description 初始化设置面包屑导航和标签导航
       */
      this.setTagNavList()
      this.addTag({
        route: this.$store.state.app.homeRoute
      })
      this.setBreadCrumb(this.$route.matched)
      // 设置初始语言
      this.setLocal(this.$i18n.locale)

      _this.$nextTick(function () {
        // os.init(); // 系统信息
      });

    },
    methods: {
      ...mapMutations([
        'setBreadCrumb',
        'setTagNavList',
        'addTag',
        'setLocal'
      ]),
      ...mapActions([
        'handleLogin'
      ]),
      // 菜单
      getMenuList: function () {
        var _this = this;
        var menuList = this.$store.getters.menuList;
        var returnMenuList = [];
        returnMenuList = menuList;// 全部菜单
        _this.menuList = returnMenuList;
      },
      // 根据权限获取菜单
      getShowMenuList: function (menuList, routerNameMenuList) {
        var _this = this;
        for (var k in menuList) {
          if (!menuList[k]) {
            continue;
          }
          var name = menuList[k].name;
          var children = menuList[k].children;
          if (routerNameMenuList.indexOf(name) > -1) {
            if (children && children.length > 0) {
              for (var i in menuList[k].children) {
                if (!menuList[k].children[i]) {
                  continue;
                }
                var name2 = menuList[k].children[i].name;
                var children2 = menuList[k].children[i].children;
                if (routerNameMenuList.indexOf(name2) > -1) {
                  if (children2 && children2.length > 0) {
                    for (var l in menuList[k].children) {
                      if (!menuList[k].children[i].children[l]) {
                        continue;
                      }
                      var name3 = menuList[k].children[i].children[l].name;
                      if (routerNameMenuList.indexOf(name3) > -1) {

                      } else {
                        menuList[k].children[i].children[l] = {};
                      }
                    }
                  }
                } else {
                  menuList[k].children[i] = {};
                }
              }
            }
          } else {
            menuList[k] = {};
          }
        }
        return menuList;
      },
      turnToPage (route) {
        let {name, params, query} = {}
        if (typeof route === 'string') name = route
        else {
          name = route.name
          params = route.params
          query = route.query
        }
        if (name.indexOf('isTurnByHref_') > -1) {
          window.open(name.split('_')[1])
          return
        }
        this.$router.push({
          name,
          params,
          query
        })
      },
      handleCollapsedChange (state) {
        this.collapsed = state
      },
      handleCloseTag (res, type, route) {
        let openName = ''
        if (type === 'all') {
          this.turnToPage('home')
          openName = 'home'
        } else if (routeEqual(this.$route, route)) {
          if (type === 'others') {
            openName = route.name
          } else {
            const nextRoute = getNextRoute(this.tagNavList, route)
            this.$router.push(nextRoute)
            openName = nextRoute.name
          }
        }
        this.setTagNavList(res)
        this.$refs.sideMenu.updateOpenName(openName)
      },
      handleClick (item) {
        this.turnToPage(item)
      },
      loginOut: function () {
        var _this = this;
        sessionStorage.setItem('logout', 1);
        Util.sessionRemove('token');
        this.$router.push({
          name: 'login'
        })
        _this.tologinOut();
      },
      tologinOut: function () {
        var _this = this;
        setTimeout(function () {
          var data = {};
          var params = {
            url: '/user/logout',
            type: Util.method.post,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              console.log('退出成功');
            } else {

            }
          }
        }, 1000);
      },
    }
  }
</script>
